<template>
  <div class="cjy-classify-list" :style="{paddingTop: '2.9rem',paddingBottom: '3rem'} "
       style="background: #F1F1F1;position:static;">
    <vertical-scroll>
      <ul class="aui-list aui-media-list commodity_list" v-if="cartList && cartList.length != 0"
          style="background: #F1F1F1;">
        <li class="aui-list-item" style="background: white">
          <div class="aui-list-item-inner">
            <label class="aui-pull-left" s>
              <input class="aui-checkbox" type="checkbox" name="demo1" v-model="isCheck" @change="changeControltyp">&nbsp;
              {{brandname}}
            </label>
            <div class="aui-pull-right text_c_gray">共{{cartNum}}件</div>
          </div>
        </li>

        <cart-regular v-if="sessionId"
                      :couponListCanBeGet="couponListCanBeGet || []"
                      :couponListCanBeUsed="couponListCanBeUsed || []"
                      type="conpon"
                      @getDiscountCoupon="getDiscountCoupon">

        </cart-regular>


        <cart-regular
            v-for=" item in normalList"
            :prodVo="item"
            type="normal"
            @showFree="showFree"
            @showChoseNum="showChoseNum"
            @searchCode="searchCode"
            @showBuyMoreLadder="showBuyMoreLadder"
            @showSelectLadder="showSelectLadder">
        </cart-regular>
        
        <li v-if="isReadyLoad && showList" v-for="(item, index) in ableList" :key="item.goodsCode"
            style="margin-top: 0.5rem;background: white">
          <cart-item ref="cartItem"
                     :showDele=" index === deleIndex"
                     @showDelButton="showDelButton"
                     @heiddenDelButton="heiddenDelButton"
                     @itemOnChecked="itemOnChecked"
                     :detail="translateDetailData(item)"
                     :isCheck="item.preorder"
                     :workingInfo="item.workingInfo"
                     :prodVoList="prodVoList"
                     :index="index">
          </cart-item>

          <cart-regular v-if=" findProdVo(item.goodsCode || item.goodscode)"
                        :prodVo="findProdVo(item.goodsCode || item.goodscode)"
                        :goodsCode="item.goodsCode || item.goodscode"
                        :brandName="item.brandname"
                        :goodsType=" item.goodsType"
                        :goodsUnit=" item.goodsUnit"
                        :regularType=" 'goods'"
                        :goodsClassCode="item.goodsclasscode"
                        @showFree="showFree"
                        @showChoseNum="showChoseNum"
                        @showBuyMoreLadder="showBuyMoreLadder"
                        @showSelectLadder="showSelectLadder">
          </cart-regular>
        </li>
        
        <li style="margin-top: 0.5rem">
          <cart-regular
            v-for=" item in giftList"
            :prodVo="item"
            type="gift"
            @showFree="showFree"
            @showChoseNum="showChoseNum"
            @showBuyMoreLadder="showBuyMoreLadder"
            @searchCode="searchCode"
            @showSelectLadder="showSelectLadder">
          </cart-regular>

        </li>

        <li
          style="width: 100%;background: white;margin:0.5rem 0 -0.4rem;height:2rem;line-height: 2rem;padding: 0 0.75rem; font-size: 0.7rem; "
          v-if="disableList.length>0 && isReadyLoad">
          <span style="display: inline-block; float: left;font-weight: 600">失效商品 {{disableNum}}件</span>
          <span style="display: inline-block; float: right;color:#EF5423 " @click="clearDisableOnClick">清空失效商品</span>
        </li>
        <li v-if="disableList.length>0 && isReadyLoad" v-for="(item, indexDis) in disableList"
            style="margin-top: 0.5rem;background: white">
          <cart-item-disable
            :detail="translateDetailData(item,true)">
          </cart-item-disable>
        </li>
      </ul>


      <div v-else-if="isLoading"></div>
      <!--购物车是空的-->
      <div v-else class="no_data">
        <img src="static/image/no_good.png" style="width:70%;"/>
        <p>购物车里没有东西哦，快去挑选吧~</p>
        <router-link class="back_home aui-btn aui-btn-outlined" tag="div" :to="{path:'home'}">逛逛首页</router-link>
      </div>
      <!--购物车是空的 end-->
    </vertical-scroll>

    <div
      style="position: absolute;bottom:5rem; left:0; height:1.8rem;background: white;border-radius: 0 0.9rem 0.9rem 0;padding: 0.2rem  1.6rem 0.15rem  0.15rem;box-shadow:0 0 2px rgba(36,36,36,0.3);line-height: 1.5rem"
      @click.stop="showBag">
      <div style="width: 100%;height: 100%;float: left;padding-right:.3rem">
        <span style="font-weight: 600;display: inline-block;">¥</span><span
        style="display: inline-block;font-size: 0.8rem;font-weight: 600">{{ parseFloat(bagPay).toFixed(2)}}</span>
      </div>
      <div
        style="height:1.4rem;width:1.4rem;background:#EF5423;border-radius: 50%;float:left;box-shadow:inset 0 0 2px rgba(36,36,36,0.3); margin-right: -1.5rem;">
        <IconBage color="white" :fontWeight="600" fontSize="1.25rem"></IconBage>
      </div>
    </div>
  </div>
</template>

<script>
  import CartItem from './CartItem/index.vue'
  import CartItemDisable from './CartItem/CartItemDisable'
  import IconBage from '../BagIcon'
  import VerticalScroll from '@/real-components/VerticalScroll'
  import {Toast} from '@/utils/toast'
  import {
    queryCart,
    queryGoodsListNormal,
    queryPromotionInfo,
    queryPromotionInfoOffLine,
    queryShoppingCartForCart,
    scanDeleteShoppingCart,
    scanQueryShoppingCartForCart,
    scanQueryPromotionInfo,
    scanUpdateShoppingCart,
    scanAddShoppingCart,
  } from '@/utils/ReturnAxios'
  import {translateDetailData} from '../../../utils/TranslateDetailDate'
  import CartRegular from '@/real-components/CartRegular/ForOffLine'
  import {mapMutations, mapGetters} from 'vuex'
  import {showLoading, hideLoading} from '@/utils/loading'
  import {MessageBox} from '@/ui-components'

  export default {
    data() {
      return {
        ableList: [], //有效商品
        disableList: [], //失效商品
        bagLsit: [], //袋子
        deleIndex: null, //展示删除状态的选项
        isCheck: true,  // 全部选中状态
        idList: [],     // 全部id列表
        detailList: [], // 选中的要删除的id列表
        bagListDetail: [],
        brandname: '宁家生鲜', //店铺名称
        checkedList: [], // 被选中的列表
        isLoading: true, // 是否显示正正在加载状态
        isAfterHttp: false, // 加载是否完成
        couponListCanBeUsed: null,
        couponListCanBeGet: null,
        aftrerDiscountMoney: 0, // 优惠金额
        discountMoney: 0,//已优惠金额
        fixedPackageList: [],
        prodVoList: [],
        normalList: [],
        giftList: [],
        isStockCountOver: false,
        sessionId: '',
        isReadyLoad: false,
        storeCode: '',
      }
    },
    components: {CartItem, CartRegular, VerticalScroll, CartItemDisable, IconBage},

    created() {
      var sessionId = localStorage.getItem('sessionId')
      this.sessionId = sessionId == 'undefined' ? '' : sessionId// 初始化sessionId
      this.storeCode = localStorage.getItem('storeCode')
      this.isCheck = this.allCheck   //获取全选状态
      this.initStoreName()
    },
    beforeCreate() {
      this.$store.commit('cjy/CLEAR_CART', null)
    },
    mounted() {
      this._initData() //初始化数据请求
    },
    beforeRouteLeave(to, form, next) {
    },
    props: {
      allCheck: {
        type: Boolean,
        default: true,
      },
      controltyp: {
        type: Number,
        default: 1
      },

    },

    watch: {
      allCheck(data) {
        this.isCheck = data //选中状态
      },
      showList(data) {
        if (!this.isAfterHttp) {
          return
        }
        this._initCheckedList()
      },

      controltyp(controltyp) {
        if (controltyp) {
          this.changePreOrder(controltyp) //改变数据欲购买中状态
        }
      },
      checkedList(data) {
        this.$store.commit('cjy/SET_OFF_LINE_SELECT_DATA', data) // 数据传回
        //申请优惠信息
        if (!this.isReadyLoad) {
          return
        }
        this.$emit('initAllCheck')
      },
      ableList(data) {
         if (!this.isReadyLoad) {
          return
        } 
        this.timeOut && clearTimeout(this.timeOut)
        this.timeOut = setTimeout(
          () => {
            if (data.length > 0) {
              this.queryRegularDetail()
            } else {
              this.initRegularDetail({})
            }
          }, 100
        )
      },

      // 监听已优惠金额
      discountMoney(data) {
        this.$store.commit('cjy/CHANGE_DISCOUNT_MONEY', data)
      },

      // ableList(data) {
      //   this.$store.commit('cjy/CHANGE_BAG_LIST')
      // }

    },

    methods: {
      translateDetailData,
      ...mapMutations('cjy', ['CLEAR_CART', 'QUERY_CART']),
      ...mapGetters(['getConfigParams']),

      showDelButton(index) {
        this.deleIndex = index
      },
      //初始化店铺名称
      initStoreName() {
        var storeList = this.storeList || []
        var storeCode = this.storeCode

        var returnList = storeList.find((item) => {
          return storeCode == item.storeCode
        })
        if (returnList) {
          this.brandname = returnList.storeName
        }
      },
      //更改化全选状态
      changePreOrder(controltyp) {
        var sessionId = this.sessionId

        if (controltyp === 1) {
          this.$store.commit('cjy/OFF_LINE_CHANGE_ALL_CHECKED', true)
        } else if (controltyp === 2) {
          this.$store.commit('cjy/OFF_LINE_CHANGE_ALL_CHECKED', false)
        }
        var isLoadShowCart = this.isLoadShowCart
        if (!sessionId && !isLoadShowCart) {
          return
        }

        setTimeout(() => {
          var config = this.config
          if (config.length == 0) {
            return
          }
          this.updataCart(config)
        }, 20)
      },
      //上传购物车的信息
      async updataCart(config) {
        // try {
        var res = await
          scanUpdateShoppingCart(config)
        res = res.data
        if (res.returncode == 0 || res.returnCode == 0) {
          Toast({
            message: res.msg,
            type: 'fail'
          })
        }
//        this.$store.commit("UPDATA_CART", res)
//         } catch (err) {
//           Toast({
//             message: '网络异常',
//             type: 'fail'
//           })
//         }
      },
      //初始化已选择商品列表
      _initCheckedList() {
        this.checkedList = this.cartList.filter((item) => {
            item = translateDetailData(item)
            return item.preorder
          }
        )
      },

      //加载动画
      animateLodding() {
        showLoading()
        setTimeout(() => {
          hideLoading()
          this.isLoading = false
        }, 3000)
      },
      // 列表选中项目变更
      itemOnChecked(config) {
        this.$emit('changeControltyp', 0)
      },
      //改变 全选按钮的控制状态
      changeControltyp() {
        setTimeout(() => {
          var data = 2
          var checked = this.isCheck
          if (checked) {
            data = 1
          }
          this.$emit('changeChecked', checked)
          this.$emit('changeControltyp', data)
        }, 20)
      },
      //隐藏删除按键
      heiddenDelButton() {
        this.deleIndex = -1
      },
      //初始化数据
      async _initData() {
        var sessionId = this.sessionId
        var isLoadShowCart = this.isLoadShowCart
        if (!sessionId && !isLoadShowCart) {
          //未登录时取本地数据
          this.$store.dispatch('cjy/queryCartFromLocal')
          this.isAfterHttp = true
          //this.getIdList()
          return
        }
        //this.queryCart() // 登陆状态申请购物车相关数据
      },
      //获取购物车数据登陆状态
      async queryCart() {
        var res = await scanQueryShoppingCartForCart()
        hideLoading()
        res = res.data
        setTimeout(() => {
          this.isReadyLoad = true
          this.$emit('initAllCheck')
        }, 20)
        this.analysisCartData(res.data)
      },
      //解析数据
      analysisCartData(data) {
        this.queryCartVuex(data) // 将购物车数据 存在中vuex
        var cartListInfro = data[0] || {}
        var regularInfo = data[1] || {}
        var bagListDetail = data[2] ? data[2][0] && data[2][0].results : []
        var shoppingCartListVOs = cartListInfro.shoppingCartListVOs || []
        var shoppingCartLists = cartListInfro.shoppingCartLists || []
        var detailList = shoppingCartListVOs.map((item) => {
          return JSON.parse(item.mallGoodsVO)
        })
        this.bagListDetail = bagListDetail
        this.detailList = detailList.concat(bagListDetail)
        hideLoading()
        this.isAfterHttp = true
        this.initRegularDetail(regularInfo)

      },
      //将数据传回Vuex
      queryCartVuex(data) {
        var activeCartList
        var storeCode = this.storeCode
        var activeCart = data.find((item) => {
          return storeCode == parseInt(item.storeCode)
        })
        if (activeCart) {
          activeCartList = activeCart.shoppingCartLists
        }
        else {
          activeCartList = []
        }
        this.$store.commit('cjy/SET_OFF_LINE_ACTIVE_DATA', activeCartList)
      },


      //获取购物车的优惠信息
      async queryRegularDetail() {
        var res
        var sessionId = this.sessionId
        if (!sessionId) {
          var selectList = this.checkedList
          if (selectList.length == 0) {
            return
          }
          var shoppingCartLists = selectList.map((item) => {
            return {
              goodsCode: item.goodsCode,
              goodsId: item.goodsId,
              goodsNum: item.goodsNum,
              goodsUnit:item.goodsunit
            }
          })

          var data = {shoppingCartLists}
          res = await  queryPromotionInfoOffLine(data)
        } else {
          var res = await scanQueryPromotionInfo()
        }
        res = res.data
        if (res.returnCode == 1) {
          this.initRegularDetail(res.data[0])
        }
      },

      //初始化优惠信息
      initRegularDetail(data) {
        var totalWorkingFee = data.totalWorkingFee || 0
        this.couponListCanBeUsed = data.couponListCanBeUsed || []
        this.couponListCanBeGet = data.couponListCanBeGet || []
        this.aftrerDiscountMoney = data.totalMoney || 0
        this.discountMoney = data.discountMoney || 0
        this.fixedPackageList = data.fixedPackageList || []
        this.prodVoList = data.calculationVO ? data.calculationVO.prodVoList : []

        //将优惠价格保存到
        this.$store.commit('cjy/INIT_PRICE', {
          aftrerDiscountMoney: this.aftrerDiscountMoney,
          discountMoney: this.discountMoney,
          totalWorkingFee
        })

        this.$store.commit('cjy/INIT_PRODVO_LIST', this.prodVoList)
        this.groupNormal()
      },

      // methods 筛选出对应商品的活动
      findProdVo(data) {
        var prod = this.prodVoList.find(
          (item) => {
            return data == item.goodsCode
          }
        )
        return prod
      },
       // 获取分组活动的数据
      groupNormal() {
        var allPromotionalVoList = []
        var mapNormal = new Map()
        var mapGift = new Map()
        this.prodVoList.map((list) => {
          if (!list.selected) {
            return
          }
          var promotionalVoList = list.promotionalVoList
          promotionalVoList.map((item) => {
            var {promId, prefRange, saleType} = item
            if (prefRange !== 1 && (saleType == 'discount' || saleType == 'overBuy' || saleType == 'fullCut' || saleType == 'fullDiscount')) {
              mapNormal.set(promId, Object.assign({}, list, {promotionalVoList: [item]}))
            } else if (prefRange !== 1 && (saleType == 'rebate' || saleType == 'buyPresent')) {
              mapGift.set(promId, Object.assign({}, list, {promotionalVoList: [item]}))
            }
          })
        })
        var mapNormalList = []
        mapNormal.forEach((item) => {
          mapNormalList.push(item)
        })

        var mapGiftList = []
        mapGift.forEach((item) => {
          mapGiftList.push(item)
        })
        this.normalList = mapNormalList
        this.giftList = mapGiftList
        // console.log(this.normalList, this.giftList, '>>>>>>>>')
      },
      //点击删除失效按键
      clearDisableOnClick() {
        MessageBox.confirm('删除商品', {title: "删除商品", message: "是否从购物车中移除售罄商品", cancelButtonText: '再想想'}).then(
          (res) => {
            this.clearDisable()
          })
      },

      //清除所有失效商品
      clearDisable() {
        var sessionId = this.sessionId
        var checkList = this.disableList
        if (!checkList || checkList.length == 0) {
          return
        }

        var shoppingCartList = []
        shoppingCartList = checkList.map(
          (item) => {
            return {rid: item.rid}
          }
        )
        this.ajaxDeleFromCart(shoppingCartList)
      },


      async ajaxDeleFromCart(shoppingCartList) {

        var ids = shoppingCartList.map((item) => {
          return item.rid
        })
        ids = ids.join(',')
        var res = await scanDeleteShoppingCart(ids)
        res = res.data
        this.deleCartVuex(shoppingCartList)
      },

      deleCartVuex(data) {
        var cartList = JSON.parse(JSON.stringify(this.cartList))
        data.map((item) => {
            for (var i = 0; cartList.length; i++) {
              if (cartList[i].rid == item.rid) {
                cartList.splice(i, 1)
                break
              }
            }
          }
        )
        this.$store.commit('cjy/SET_OFF_LINE_ACTIVE_DATA', cartList)
      },


      //添加商品到购物车
      async addGoods(goodsCodeList, isFirst) {
        var res
        var detailList = this.detailList
        var newDetailList
        var barCode = goodsCodeList[0] ? goodsCodeList[0].goodsCode : ''
        var config = goodsCodeList.map((item) => {
          return {
            goodsId:item.goodsId,
            goodsCode: '',
            goodsNum: item.goodsNum,
            storeCode: this.storeCode,
            barCode: item.goodsCode,
          }
        })
        this.animateLodding()
        res = await scanAddShoppingCart(config)
        res = res.data
        if (isFirst) {
          this.queryCart()
        }
        hideLoading()
        if (res.returncode == 0 || res.returnCode == 0) {
          Toast({
            message: '未识别出商品，请咨询身边店员',
            type: 'fail'
          })
          return
        } else {
          Toast({
            message: '加入购物车成功',
            type: 'success'
          })
        }
        if (isFirst) {
          return
        }
        hideLoading()

        var data = res.data[0]
        var shoppingCartLists = data.shoppingCartLists
        var shoppingCartListVOs = data.shoppingCartListVOs
        shoppingCartListVOs.map((item) => {
          var mallGoodsVO = JSON.parse(item.mallGoodsVO)
          var isFind = detailList.find(list => {
            return list.goodscode == item.goodscode
          })
          isFind || detailList.push(mallGoodsVO)
        })
        this.detailList = detailList
        this.$store.commit('cjy/SET_OFF_LINE_ACTIVE_DATA', shoppingCartLists)
      },

//用于组建间的时间传递
      showSelectLadder(data) {
        this.$emit('showSelectLadder', data)
      },

      showBuyMoreLadder(data) {
        this.$emit('showBuyMoreLadder', data)
      },

      getDiscountCoupon() {
        var data = {
          couponListCanBeUsed: this.couponListCanBeUsed,
          couponListCanBeGet: this.couponListCanBeGet
        }
        this.$emit('getDiscountCoupon', data)
      },

      showChoseNum(data) {
        this.$emit('showChoseNum', data)
      },

      showFree(data) {
        this.$emit('showFree', data)
      },

      showBag() {
        this.$emit('showBag', this.bagListDetail)
      },
      searchCode() {
        this.$emit('searchCode')
      }
    },

    computed: {
      // 库存阙值
      stockThreshold() {
        var getConfigParams = this.getConfigParams || {}
        return getConfigParams.stockThreshold || 0
      },
      //是否本地计加入购物车
      isLoadShowCart() {
        return this.$store.state.cjy.isLoadShowCart
      },
      // 获取购物车列表
      cartList() {
        return this.$store.getters['cjy/offLineAcitveData']
      },
      // 展示列表
      config() {
        var preorder
        var cartList = this.cartList
        if (this.controltyp == 1) {
          preorder = true
        } else {
          preorder = false
        }

        var cartList = cartList.filter((item) => {
          return item.goodsType != 8
        })

        if (cartList) {
          return cartList.map((item) => {
            return {
              goodsId:item.goodsId,
              goodsNum: item.goodsNum,
              preorder: preorder,
              rid: item.rid,
              serve: item.serve || '',
              goodsDeliveryType: item.goodsDeliveryType || '',
              workingInfo: item.workingInfo || '',
            }
          })
        } else {
          return []
        }
      },
      //展示数据列表
      showList() {
        var showList = []
        var cartList = this.cartList
        var detailList = this.detailList
        var ableList = []
        var disableList = []
        var bagLsit = []
        cartList.map((cart) => {
          var detail = detailList.find((item) => {
            return item && (parseInt(cart.goodsId) == parseInt(item.goodsid))
          })
          Object.assign(cart, detail || {})
          showList.push(cart)
        })
        this.ableList = showList.filter((item) => {
          var item = translateDetailData(item)
          return item.lastStockCountNum > 0 && item.goodsType != 8
        })
        this.disableList = showList.filter((item) => {
          var item = translateDetailData(item)
          return !item.goodsPrice || item.lastStockCountNum < 0
        })
        this.bagLsit = showList.filter((item) => {
          var item = translateDetailData(item)
          return item.goodsType == 8
        })
        return showList
      },
      //购物车数量
      cartNum() {
        var ableList = this.ableList
        var cartNum = 0
        this.ableList.map((item) => {
          if (item.goodsType == 7) {
            cartNum += 1
          } else {
            cartNum += item.goodsNum
          }
        })
        return cartNum + this.bagNum
      },

      bagPay() {
        var bagPay = 0
        this.bagLsit.map((item) => {
          var item= translateDetailData(item)
          var goosNum = item.goodsNum || 0
          var goodsPrice = item.goodsPrice || 0
          bagPay += goosNum * goodsPrice
        })
        return bagPay
      },
      bagNum() {
        var bagNum = 0
        var bagLsit = this.bagLsit
        bagLsit.map((item) => {
          var item= translateDetailData(item)
          var goosNum = item.goodsNum || 0
          bagNum += goosNum
        })
        return bagNum
      },

      storeList() {
        return this.$store.getters['qxz/getStoreList']
      },
      disableNum() {
        var goodsNum = 0
        this.disableList.map((item) => {
          goodsNum += item.goodsNum
        })
        return goodsNum
      },
    },

  }
</script>


<style scoped>
  .cjy-classify-list {
    width: 100%;
    height: 100%;
  }

</style>
